<?php
namespace app\admin\controller;

use app\common\model\Orders;
use app\common\model\OrdersItem;
use app\common\model\OrdersItemChange;
use app\common\model\OrdersItemReject;
use think\Session;
use think\Db;
use app\admin\library\orders\LibraryOrders;
use app\common\model\ProjectLog;
use app\admin\library\baiduApi\BaiduApi;
use app\admin\library\account\UserService;

class IndexController extends BaseController
{
    public function index()
    {	
    	$menus = [
    		[
    			'name'		=> '商品管理',
    			'icon'		=> 'fa-google',
    			'role_ids'	=> [1,2,3,4,5,6,7,0],
				'id'		=> 1,
    			'children'	=> [
    				[
						'id'		=> 2,
    					'name'	=> '分类列表',
    					'url'	=> 'Goods/cateList',
    					'role_ids'	=> [1,2,3,5,6,7,0]
    				],
    				[
						'id'		=> 3,
    					'name'	=> '品牌列表',
    					'url'	=> 'Brand/lists',
    					'role_ids'	=> [1,2,3,5,6,7,0]
    				],
    				[
						'id'		=> 4,
    					'name'	=> '商品列表',
    					'url'	=> 'Goods/lists',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
					],
					// [
    				// 	'name'	=> '库存管理',
    				// 	'url'	=> 'Goods/stock',
    				// 	'role_ids'	=> [1,2,3,4,5,6,7,0]
    				// ]
    			]
    		],
			[
				'id'		=> 5,
    			'name'		=> '订单管理',
    			'icon'		=> 'fa-credit-card',
    			'role_ids'	=> [1,2,3,4,5,6,7,0],
    			'children'	=> [
    				[
						'id'    => 37,
    					'name'	=> '订单列表',
    					'url'	=> 'Orders/lists',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
    				// [
    				// 	'name'	=> '订单明细',
    				// 	'url'	=> 'Orders/itemList',
    				// 	'role_ids'	=> [1,2,3,4,5]
    				// ],
                    // [
                    //     'name'  => '待发货订单',
                    //     'url'   => 'Orders/stockList',
                    //     'role_ids'  => [1,2,3,4,5]
                    // ],
    				[
						'id'		=> 6,
    					'name'	=> '换货订单',
    					'url'	=> 'Orders/changeList',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
    				[
						'id'		=> 7,
    					'name'	=> '添加订单',
    					'url'	=> 'Orders/add',
    					'role_ids'	=> [1,5,6,7,0]
    				]
    			]
    		],
    		[
				'id'		=> 8,
    			'name'		=> '报单管理',
    			'icon'		=> 'fa-trademark',
    			'role_ids'	=> [1,3,4,5,0],
    			'children'	=> [
    				[
						'id'		=> 9,
    					'name'	=> '待报订单',
    					'url'	=> 'Purchase/orderItemList',
    					'role_ids'	=> [1,3,4,5,0]
    				],
    				[
						'id'		=> 10,
    					'name'	=> '报单记录',
    					'url'	=> 'Purchase/lists',
    					'role_ids'	=> [1,3,4,5,0]
    				]
    			]
    		],
    		[
				'id'		=> 11,
    			'name'		=> '收发货管理',
    			'icon'		=> 'fa-exchange',
    			'role_ids'	=> [1,2,3,4,6,7,0],
    			'children'	=> [
    				[
						'id'		=> 12,
    					'name'	=> '到货登记',
    					'url'	=> 'StockIn/purchaseList',
    					'role_ids'	=> [1,2,7,0]
    				],
    				[
						'id'		=> 13,
    					'name'	=> '到货记录',
    					'url'	=> 'StockIn/lists',
    					'role_ids'	=> [1,2,3,4,6,7,0]
    				],
    				[
						'id'		=> 14,
    					'name'	=> '发货记录',
    					'url'	=> 'Express/lists',
    					'role_ids'	=> [1,2,3,4,6,7,0]
    				],
    			]
    		],
    		[
				'id'		=> 15,
    			'name'		=> '基础信息',
    			'icon'		=> 'fa-cog',
    			'role_ids'	=> [1,3,4,5,6,7,0],
    			'children'	=> [
    				[
						'id'		=> 16,
    					'name'	=> '地址列表',
    					'url'	=> 'Area/lists',
    					'role_ids'	=> [1,3,5,6,7,0]
    				],
    				[
						'id'		=> 17,
    					'name'	=> '档口列表',
    					'url'	=> 'Stall/lists',
    					'role_ids'	=> [1,3,4,5,0]
    				]
    			]
    		],
    		[
				'id'		=> 18,
    			'name'		=> '账号管理',
    			'icon'		=> 'fa-user-circle-o',
    			'role_ids'	=> [3,0],
    			'children'	=> [
    				[
						'id'		=> 19,
    					'name'	=> '添加账号',
    					'url'	=> 'Account/add',
    					'role_ids'	=> [3,0]
    				],
    				[
						'id'		=> 20,
    					'name'	=> '账号列表',
    					'url'	=> 'Account/lists',
    					'role_ids'	=> [3,0]
    				],
					[
						'id'		=> 38,
    					'name'	=> '角色列表',
    					'url'	=> 'Account/role',
    					'role_ids'	=> [3,0]
    				],
    				[
						'id'		=> 39,
    					'name'	=> '菜单列表',
    					'url'	=> 'Account/menu',
    					'role_ids'	=> [3,0]
    				],
                    // [
                    //     'name'  => '访问记录',
                    //     'url'   => 'Account/pageloglist',
                    //     'role_ids'  => [10]
                    // ]
    			]
    		],
			[
				'id'		=> 21,
    			'name'		=> '团队管理',
    			'icon'		=> 'fa-group',
    			'role_ids'	=> [3,0],
    			'children'	=> [
    				[
						'id'		=> 22,
    					'name'	=> '团队列表',
    					'url'	=> 'organization/lists',
    					'role_ids'	=> [3,0]
    				],
					[
						'id'		=> 23,
    					'name'	=> '添加账号',
    					'url'	=> 'organization/add',
    					'role_ids'	=> []
    				],
    			]
    		],
			[
				'id'		=> 24,
    			'name'		=> '售后管理',
    			'icon'		=> 'fa-credit-card',
    			'role_ids'	=> [1,2,3,4,5,6,7,0],
    			'children'	=> [
    				[
						'id'		=> 25,
    					'name'	=> '退货订单',
    					'url'	=> 'Orders/returnList',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 26,
    					'name'	=> '取消订单',
    					'url'	=> 'Orders/refundList',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				]
    			]
    		],
			[
				'id'		=> 27,
    			'name'		=> '财务管理',
    			'icon'		=> 'fa-credit-card',
    			'role_ids'	=> [3,6,0],
    			'children'	=> [
					[
						'id'		=> 28,
    					'name'	=> '现金报表',
    					'url'	=> 'Orders/financeList',
    					'role_ids'	=> [3,6,0]
    				]
    			]
    		],
			[
				'id'		=> 29,
    			'name'		=> '仓库管理',
    			'icon'		=> 'fa-google',
    			'role_ids'	=> [1,2,3,4,5,6,7,0],
    			'children'	=> [
					[
						'id'		=> 30,
    					'name'	=> '仓库列表',
    					'url'	=> 'Warehouse/stock',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 31,
    					'name'	=> '库存查询',
    					'url'	=> 'Warehouse/room',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 32,
    					'name'	=> '库存盘点',
    					'url'	=> 'Warehouse/pandian',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 33,
    					'name'	=> '入库列表',
    					'url'	=> 'Warehouse/otpurchase',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 34,
    					'name'	=> '添加入库',
    					'url'	=> 'Warehouse/add_otpurchase',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 35,
    					'name'	=> '出库列表',
    					'url'	=> 'Warehouse/otsale',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				],
					[
						'id'		=> 36,
    					'name'	=> '添加出库',
    					'url'	=> 'Warehouse/add_otsale',
    					'role_ids'	=> [1,2,3,4,5,6,7,0]
    				]
    			]
    		],
    	];
    	$role_id = Session::get('role_id');

        // if ($role_id==0) {
        //     $role_id = 3;
        // }
		
		$uid = Session::get('uid');
		$data = UserService::info($uid, true, true);
		
		// echo '<pre/>';
		// var_dump($data);die;

    	$r_menus = [];	//角色对应的菜单
		// 旧的
    	// foreach ($menus as $menu) {
    	// 	if ( in_array($role_id, $menu['role_ids']) ){
        //         $row = [
        //         	'name'	=> $menu['name'],
        //         	'icon'	=> $menu['icon'],
		// 			'id'	=> $menu['id'],
    	// 		];
    	// 		$row['children'] = [];
    	// 		foreach ($menu['children'] as $child) {
    	// 			if ( in_array($role_id, $child['role_ids']) ){
    	// 				$row['children'][] = [
    	// 					'name'	=> $child['name'],
    	// 					'url'	=> $child['url'],
		// 					'id'	=> $child['id'],
    	// 				];
    	// 			}
    	// 		}
    	// 		$r_menus[] = $row;
        //     }
    	// }
		
		// 新的 
		$r_menus = $data['menus'];
    	$this->assign('menus', $r_menus);
        if ($role_id==10) {
            $this->assign('menus', $menus);
        }
        return view();
    }
	public function test(){
		return view();
	}
    public function publicT()
    {
		$library_orders = new LibraryOrders();
		$order_info = $library_orders->getList();
		// dump($order_info);die;
    	return view('',[
			'order_info'=>$order_info
		]);
    }
    public function cache()
    {
        return view();
    }
    public function updatePurchase()
    {        
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $page_size = 500;
        $where = [
            // 'id'    => ['>', 5000]
        ];

        $model = Db::name('purchase');
        $total = $model->where($where)->count();
        $rows = $model->where($where)->page($page, $page_size)->select();
        
        //订单信息
        $oi_map = Db::name('orders_item')
                            ->alias('oi')
                            ->join('__ORDERS__ o', 'o.id = oi.order_id')
                            ->join('__GOODS__ g', 'g.id = oi.goods_id')
                            ->where('oi.id', 'in', array_column($rows,'order_item_id'))
                            ->column('oi.id,o.acct_id,goods_id','oi.id');
        //print_r($oi_map);exit;

        $affected = 0;
        foreach ($rows as &$row) {
            $oi = $oi_map[$row['order_item_id']];
            $info = [
                'c_goods_id'   => $oi['goods_id'],
                'c_saler_id'   => $oi['acct_id']
            ];

            $res = $model->where('id', $row['id'])->update($info);

            if ($res === false) {
                $this->error('错误:' . $row['id']);
            } else {
                $affected += $res;
            }
        }
        $data = [
            'page'      => $page,
            'page_size' => count($rows),    
            'total'     => $total,
            'affected'  => $affected
        ];
        $this->success('成功','',$data);
    }
	/**
	 * 订单提醒
	 */
	public function orderRemark(){
		$project_log_model = new ProjectLog();
		// 正常订单未发货
		$res = OrdersItem::with(['orderInfo'])->whereIn('progress',[1,2,3])->select()->each(function($item) use ($project_log_model){
			// 超过48小时d订单，发起消息通知
			$time_res = ((time() - $item['add_time'])/3600)>48;
			$order_info = $item['order_info'];
			$log_data = [
				'account_id' => Session::get('uid'),
				'remark' => '订单列表,'.'客户:'.$order_info['cust'].','.'订单号'.$order_info['order_no'],
				'source_id' => $item['id'],
				'type' => 'orderRemark',
				'organization_id' => ''
	
			];
			$is_source_id = $project_log_model->where('source_id',$item['id'])->where('type','orderRemark')->find();
			if($time_res&&!$is_source_id){
				$project_log_model->add($log_data);
			}
			return;
			
		});
		// 换货订单 未发货
		 //订单信息
		 $change_model = new OrdersItemChange();
		 $oc_res = $change_model
		 ->alias('oc')
		 ->join('__ORDERS_ITEM__ oi', 'oc.order_item_id = oi.id')
		 ->join('__ORDERS__ o', 'oi.order_id = o.id')
		 ->where('exp_no', '')
		 ->field('oc.*,o.order_no,o.cust')
		 ->select()
		 ->each(function($item) use ($project_log_model){
			// 超过48小时d订单，发起消息通知
			$time_res = ((time() - $item['add_time'])/3600)>48;

			
			$log_data = [
				'account_id' => Session::get('uid'),
				'remark' => '换货订单,'.'客户:'.$item['cust'].','.'订单号'.$item['order_no'],
				'source_id' => $item['id'],
				'type' => 'orderRemarkChange',
				'organization_id' => ''
	
			];
			$is_source_id = $project_log_model->where('source_id',$item['id'])->where('type','orderRemarkChange')->find();
			if($time_res&&!$is_source_id){
				$project_log_model->add($log_data);
			}
			return;
			
		});

		 // 订单 未发货
		 //订单信息
		 $reject_model = new OrdersItemReject();
		 $oj_res = $reject_model
		 ->alias('oc')
		 ->join('__ORDERS_ITEM__ oi', 'oc.order_item_id = oi.id')
		 ->join('__ORDERS__ o', 'oi.order_id = o.id')
		 ->where('exp_no', null)
		 ->field('oc.*,o.order_no,o.cust')
		 ->select()
		 ->each(function($item) use ($project_log_model){
			// 超过48小时d订单，发起消息通知
			$time_res = ((time() - $item['add_time'])/3600)>48;

			
			$log_data = [
				'account_id' => Session::get('uid'),
				'remark' => '退货订单,'.'客户:'.$item['cust'].','.'订单号'.$item['order_no'],
				'source_id' => $item['id'],
				'type' => 'orderRemarkReject',
				'organization_id' => ''
	
			];
			$is_source_id = $project_log_model->where('source_id',$item['id'])->where('type','orderRemarkReject')->find();
			if($time_res&&!$is_source_id){
				$project_log_model->add($log_data);
			}
			return;
			
		});
	}
	/**
	 * 获取address_assess_token
	 */
	public function get_access_token(){
		$baidu = new BaiduApi();
		$access_token = $baidu->run();
		$access_token = json_decode($access_token,true);
		Db::name('config_value')->where('config_key','address_access_token')->update(['value'=>$access_token['access_token']]);
	}
	/**
	 * 智能识别地址
	 * 上海市浦东新区纳贤路701号百度上海研发中心 F4A000 张三
	 */
	public function get_address(){
		$text = $this->request->param('text');
		$baidu = new BaiduApi();
		$access_token = Db::name('config_value')->where('config_key','address_access_token')->find();
		$res = $baidu->getAddrss($access_token['value'],$text);
		$this->success('成功','',$res);
	}
	
    /**
	 * 首页数据
	 */
    public function home($type = 1){
        $date2 = time();
		switch ($type) {
			case 1:
				$date1 = $date2 - 365*24*60*60;
				break;
			case 2:
				$date1 = $date2 - 90*24*60*60;
				break;
			case 3:
				$date1 = $date2 - 30*24*60*60;
				break;
			
			default:
				$date1 = $date2 - 24*60*60;
				break;
		}
		$date1 = date('Y-m-d', $date1);
		$date2 = date('Y-m-d', $date2);
		$total_list = LibraryOrders::getOrderData(['date1' => $date1,'date2' => $date2,]);

		$this->success('成功','',$total_list[1]);

    }
}